package com.bandaotixi.cashier.api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.bandaotixi.cashier.api.common.model.Option;
import com.bandaotixi.cashier.api.common.result.PageResult;
import com.bandaotixi.cashier.api.common.result.Result;
import com.bandaotixi.cashier.api.system.model.entity.Dict;
import com.bandaotixi.cashier.api.system.model.entity.DictItem;
import com.bandaotixi.cashier.api.system.model.query.DictItemPageQuery;
import com.bandaotixi.cashier.api.system.model.query.DictPageQuery;
import com.bandaotixi.cashier.api.system.service.DictItemService;
import com.bandaotixi.cashier.api.system.service.DictService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 字典控制层
 */
@RestController
@RequestMapping("/dict")
@RequiredArgsConstructor
public class DictController {

    private final DictService dictService;
    private final DictItemService dictItemService;


    /**
     * 字典分页列表
     */
    @GetMapping("/page")
    public PageResult<Dict> getDictPage(DictPageQuery queryParams) {
        Page<Dict> result = dictService.lambdaQuery().like(StringUtils.hasLength(queryParams.getKeywords()), Dict::getName, queryParams.getKeywords())
                .page(queryParams.page());
        return PageResult.success(result);
    }


    /**
     * 字典列表
     */
    @GetMapping
    public Result<List<Option<String>>> getDictList() {
        List<Option<String>> list = dictService.lambdaQuery().eq(Dict::getStatus, 1).list()
                .stream().map(item ->
                        new Option<>(item.getDictCode(), item.getName()))
                .toList();
        return Result.success(list);
    }

    /**
     * 字典表单数据
     */
    @GetMapping("/{id}/form")
    public Result<Dict> getDictForm(@PathVariable Long id) {
        return Result.success(dictService.getById(id));
    }

    /**
     * 新增字典
     */
    @PostMapping
    @SaCheckPermission("sys:dict")
    public Result<?> saveDict(@Valid @RequestBody Dict data) {
        Assert.hasText(data.getDictCode(), "字典编码不能为空");
        Assert.isTrue(dictService.lambdaQuery().eq(Dict::getDictCode, data.getDictCode()).count() == 0, "字典编码已存在");
        boolean result = dictService.saveOrUpdate(data);
        return Result.judge(result);
    }

    /**
     * 修改字典
     */
    @PutMapping("/{id}")
    @SaCheckPermission("sys:dict")
    public Result<?> updateDict(@PathVariable Long id, @RequestBody Dict data) {
        Assert.isTrue(id.equals(data.getId()), "参数错误");
        Assert.hasText(data.getDictCode(), "字典编码不能为空");
        Assert.isTrue(dictService.lambdaQuery().eq(Dict::getDictCode, data.getDictCode()).ne(Dict::getId, id).count() == 0, "字典编码已存在");
        boolean status = dictService.updateById(data);
        return Result.judge(status);
    }

    /**
     * 删除字典
     */
    @DeleteMapping("/{ids}")
    @SaCheckPermission("sys:dict")
    public Result<?> deleteDictionaries(@PathVariable String ids) {
        dictService.deleteDictByIds(Arrays.stream(ids.split(",")).toList());
        return Result.success();
    }


    //---------------------------------------------------
    // 字典项相关接口
    //---------------------------------------------------

    /**
     * 字典项分页
     */
    @GetMapping("/{dictCode}/items/page")
    public PageResult<DictItem> getDictItemPage(@PathVariable String dictCode, DictItemPageQuery queryParams) {
        queryParams.setDictCode(dictCode);
        Page<DictItem> result = dictItemService.lambdaQuery()
                .like(StringUtils.hasLength(queryParams.getKeywords()), DictItem::getLabel, queryParams.getKeywords())
                .eq(StringUtils.hasLength(queryParams.getDictCode()), DictItem::getDictCode, queryParams.getDictCode())
                .page(queryParams.page());
        return PageResult.success(result);
    }

    /**
     * 字典项列表
     */
    @GetMapping("/{dictCode}/items")
    public Result<List<DictItem>> getDictItems(@PathVariable String dictCode) {
        List<DictItem> list = dictItemService.lambdaQuery()
                .eq(DictItem::getDictCode, dictCode)
                .eq(DictItem::getStatus, 1)
                .orderByAsc(DictItem::getSort)
                .list();
        return Result.success(list);
    }

    /**
     * 新增字典项
     */
    @PostMapping("/{dictCode}/items")
    @SaCheckPermission("sys:dict")
    public Result<Void> saveDictItem(@PathVariable String dictCode, @Valid @RequestBody DictItem formData) {
        formData.setDictCode(dictCode);
        boolean result = dictItemService.save(formData);
        return Result.judge(result);
    }

    /**
     * 字典项表单数据
     */
    @GetMapping("/{dictCode}/items/{itemId}/form")
    public Result<DictItem> getDictItemForm(@PathVariable String dictCode, @PathVariable Long itemId) {
        DictItem formData = dictItemService.getById(itemId);
        return Result.success(formData);
    }

    /**
     * 修改字典项
     */
    @PutMapping("/{dictCode}/items/{itemId}")
    @SaCheckPermission("sys:dict")
    public Result<?> updateDictItem(@PathVariable String dictCode, @PathVariable Long itemId, @RequestBody DictItem formData) {
        formData.setId(itemId);
        formData.setDictCode(dictCode);
        boolean status = dictItemService.updateById(formData);
        return Result.judge(status);
    }

    @DeleteMapping("/{dictCode}/items/{itemIds}")
    @SaCheckPermission("sys:dict")
    public Result<Void> deleteDictItems(@PathVariable String dictCode, @PathVariable String itemIds) {
        List<Long> idList = Arrays.stream(itemIds.split(",")).map(Long::parseLong).toList();
        dictItemService.removeByIds(idList);
        return Result.success();
    }

}
